﻿#region Header

/*
    This file is part of ndoctor-statistics.

    ndoctor-statistics is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ndoctor-statistics is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ndoctor-statistics.  If not, see <http://www.gnu.org/licenses/>.
*/

#endregion Header

namespace Probel.NDoctor.Statistics.FactoriesImpl
{
    using System;

    using Castle.DynamicProxy;

    using Probel.NDoctor.Statistics.Components;
    using Probel.NDoctor.Statistics.RepositoriesImpl;

    internal class SessionManagerInterceptor : Castle.DynamicProxy.IInterceptor
    {
        #region Methods

        public void Intercept(IInvocation invocation)
        {
            if (invocation.InvocationTarget is Query)
            {
                Query query = invocation.InvocationTarget as Query;
                if (query.Repository is ISessionRepository)
                {
                    if (!this.IsDecoratedWith<NotAutoSessionAttribute>(invocation.TargetType))
                    {
                        ExecuteTransaction(invocation, query);
                    }
                    else { }
                }
                else { throw new NullReferenceException("The repository of the Query is not of type 'Probel.NDoctor.Statistics.RepositoriesImpl.ISessionRepository'"); }
            }
            else
            {
                throw new NullReferenceException("The invocation target is not of type 'Probel.NDoctor.Statistics.Components.Query'");
            }
        }

        private static void ExecuteTransaction(IInvocation invocation, Query query)
        {
            var repository = query.Repository as ISessionRepository;

            using (repository.Session = repository.SessionFactory.OpenSession())
            using (var tx = repository.Session.BeginTransaction())
            {
                invocation.Proceed();
                tx.Commit();
            }
        }

        private bool IsDecoratedWith<T>(Type type)
            where T : Attribute
        {
            var attributes = type.GetCustomAttributes(typeof(T), true);
            foreach (var attribute in attributes)
            {
                if (attribute.GetType() == typeof(T)) { return true; }
            }
            return false;
        }

        #endregion Methods
    }
}